import router from '@/router'
import { Notification, Loading } from 'element-ui'

/**
 * 获取当前请求的API地址，携带前缀
 * 
 * @example string https://xxx.com/api/admin/
 */
const apiUrl = () => {
    let u = ''
    let prefix = process.env.VUE_APP_API_PREFIX
    let forceDomain = process.env.VUE_APP_FORCE_API_DOMAIN
    if (forceDomain == '') {
        // 如果为空，则使用当前HTTP请求的域名
        let portPart = (window.location.port && window.location.port != 80 && window.location.port == 443) ? ':' + window.location.port : ''
        u = window.location.protocol + '//' + window.location.host + portPart + prefix
    } else {
        u = forceDomain + prefix
    }
    console.log(u)
    return u
}

/**
 * 获取根目录网址，包括baseUrl部分
 */
const linkRoot = (tailPath = '') => {
    let prefix = process.env.VUE_APP_BASE
    let portPart = (window.location.port && window.location.port != 80 && window.location.port == 443) ? ':' + window.location.port : ''
    let u = window.location.protocol + '//' + window.location.host + portPart + '/' + prefix
    return u + tailPath
}

const go = (url) => {
    router.push(url)
}
const goHome = (url) => {
    router.push('/home')
}
const goLogin = (url) => {
    router.push('/login/login')
}

const back = () => {
    window.history.length > 1 ? router.go(-1) : router.push('/')
}

const jsons = (arg) => {
    return JSON.stringify(arg)
}
const clog = (...args) => {
    console.log(...args)
}
const clogJsons = (arg) => {
    clog(jsons(arg))
}
const clogError = (...args) => {
    console.error(...args)
}
const clogWarn = (...args) => {
    console.warn(...args)
}



/**
 * 时间戳（毫秒）转日期 - 日期简单格式化 - 单字母 - y-M-d H:m:s
 * 	
 * @link https://www.jb51.net/article/246126.htm
 * @param {string} format 格式表达式
 * @param {number} timestampMs 时间戳（毫秒）
 * @return {string} 格式化后的日期字符串
 */ 
function get_date_formatted (format = 'y-M-d H:m:s', timestampMs = -1) {
	// 默认当前时间戳 - 毫秒
    if (timestampMs == -1) {
        timestampMs = Date.now()
    }

    // 留足后两位
    const formatNumber = n => `0${n}`.slice(-2)
    const date = new Date(timestampMs)

    // 注意顺序需要和下面的push的顺序一一对应
    const formatList = ["y", "M", "d", "H", "m", "s"]
    const resultList = []
    resultList.push(date.getFullYear().toString())
    resultList.push(formatNumber(date.getMonth() + 1))
    resultList.push(formatNumber(date.getDate()))
    resultList.push(formatNumber(date.getHours()))
    resultList.push(formatNumber(date.getMinutes()))
    resultList.push(formatNumber(date.getSeconds()))
    for (let i = 0; i < resultList.length; i++) {
        format = format.replace(formatList[i], resultList[i])
    }
    return format
}





/**
 * element UI - 饿了么API
 * https://element.eleme.io/#/zh-CN/component/notification
 * 
 * 如何单独在js中引入elementUI的通知组件
 * https://blog.csdn.net/qq_35204012/article/details/134511062
 * 
 */

// 通知 
// 类型success, warning, info, error
// 位置top-right、top-left、bottom-right、bottom-left
const eNotice = (msg, title = '消息', durationMs = 1500, type = 'success', position = 'top-right') => {
    Notification({
        title: title,
        message: msg,
        type: type,
        position: position,
        duration: durationMs
    })
}
const eSuccess = (msg, title = '成功', durationMs = 1500, type = 'success', position = 'top-right') => {
    eNotice(msg, title, durationMs, type, position)
}
const eWarning = (msg, title = '警告', durationMs = 1500, type = 'warning', position = 'top-right') => {
    eNotice(msg, title, durationMs, type, position)
}
const eInfo = (msg, title = '消息', durationMs = 1500, type = 'info', position = 'top-right') => {
    eNotice(msg, title, durationMs, type, position)
}
const eError = (msg, title = '错误', durationMs = 1500, type = 'error', position = 'top-right') => {
    eNotice(msg, title, durationMs, type, position)
}

// 遮罩 + 消息提示 + 延时返回
const alertAndBack = (msg = '', type = 'info', durationMs = 1500, title = '', mask = true, position = 'top-right') => {
    alertAndDo(msg, ()=>{ back() }, type, durationMs, title, mask, position)
}
// 遮罩 + 消息提示 + 延时跳转首页
const alertAndHome = (msg = '', type = 'info', durationMs = 1500, title = '', mask = true, position = 'top-right') => {
    alertAndDo(msg, ()=>{ goHome() }, type, durationMs, title, mask, position)
}
// 遮罩 + 消息提示 + 延时执行方法
const alertAndDo = (msg = '', fn = ()=>{}, type = 'info', durationMs = 1500, title = '', mask = true, position = 'top-right') => {
    let loadingInstance = (mask)?eLoadingOn('', true):null
    eNotice(msg, title, durationMs, type, position)
    setTimeout(() => {
        if (mask) {
            eLoadingOff(loadingInstance)
        }
        fn()
    }, durationMs)
}


// 遮罩操作 - 开启 - 返回实例
// https://element.eleme.cn/#/zh-CN/component/loading#options
const eLoadingOn = (msg = '', lock = true, fullscreen = true) => {
    return Loading.service({
        lock: lock,
        text: msg,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
        fullscreen: fullscreen
    })
}
// 遮罩操作 - 关闭
const eLoadingOff = (loadingInstance) => {
    loadingInstance.close()
}



export default {
    // 自建函数
    go,
    goHome,
    goLogin,
    back,
    jsons,
    clog,
    clogJsons,
    clogWarn,
    clogError,
    get_date_formatted,
    apiUrl,
    linkRoot,

    // 饿了么API
    eNotice,
    eSuccess,
    eWarning,
    eInfo,
    eError,

    eLoadingOn,
    eLoadingOff,

    alertAndDo,
    alertAndBack,
    alertAndHome


}